<template>
  <scroll class="suggest"
          :data="result"
          :pull-up="pullUp"
          @scrollToEnd="searchMore"
          ref="suggest"
  >
    <ul class="suggest-list">
      <li class="suggest-item"
          v-for="(item,index) in result"
          :key="index"
          @click="selectItem(item)"
      >
        <div class="icon">
          <i :class="getIconCls(item)"></i>
        </div>
        <div class="name">
          <p class="text" v-html="getListText(item)"></p>
        </div>
      </li>
      <loading v-show="hasMore"></loading>
    </ul>
    <div class="no-result-wrapper" v-show="!hasMore&&!result.length">
      <no-result :title="title"></no-result>
    </div>
  </scroll>
</template>

<script type="text/ecmascript-6">
  import Scroll from 'base/scroll/scroll'
  import NoResult from 'base/no-result/no-result'
  import {getSearchSongList} from 'api/search'
  import {createSongForSearch} from 'common/js/song'
  import Loading from 'base/loading/loading'
  import {SingerForSearch} from 'common/js/singer'
  import {mapMutations, mapActions} from 'vuex'
  // 歌手类型
  const SINGER = 'singer'
  // 每页的显示歌曲的数目
  const PERPAGE = 20

  export default {
    props: {
      query: {
        type: String,
        default: ''
      },
      showSinger: {
        type: Boolean,
        default: true
      }
    },
    data () {
      return {
        // 查询结果的页数
        page: 1,
        // 查询到的数据
        result: [],
        // 上拉刷新
        pullUp: true,
        // 是否下拉还有数据
        hasMore: true,
        // 无查询结果
        title: '查询无果'
      }
    },
    methods: {
      // 点击歌手进入详情页
      selectItem (item) {
        // console.log(item)
        if (item.type === SINGER) {
          this.singer = new SingerForSearch({
            id: item.singerID,
            name: item.singerName
          })
          this.$router.push({
            path: '/search/item.singerID'
          })
          this.setSinger(this.singer)
        } else {
          this.insertSong(item)
        }
        // 派发保存搜索历史的事件
        this.$emit('saveHistory')
      },
      // 滚动到底时刷新
      searchMore () {
        // 判断是否已经达到获取数据的最大值
        if (!this.hasMore) {
          return
        }
        // 查询下一页
        this.page++
        getSearchSongList(this.query, this.page).then((res) => {
          const data = res.data.data
          this.result = this.result.concat(this._formateData(data))
          this._checkMore(data)
        })
      },
      // 判断是否查询到歌曲是否到最后一个了
      _checkMore (data) {
        const song = data.song
        if (!song.list.length || (song.curnum + song.curpage * PERPAGE) > song.totalnum) {
          this.hasMore = false
        }
      },
      // 搜索结果的文字
      getListText (item) {
        if (item.type === SINGER) {
          return item.singerName
        } else {
          return `${item.name}-${item.singer}`
        }
      },
      // 为搜索列表，根据歌手或歌曲显示不同的图标
      getIconCls (item) {
        if (item.type === SINGER) {
          return 'icon-mine'
        } else {
          return 'icon-music'
        }
      },
      // 处理格式化返回的数据
      _search () {
        // 重新输入关键词的时候要滚动到第一页
        // 不然就会停留在上次查询的位置
        this.page = 1
        this.hasMore = true
        this.$refs.suggest.scrollTo(0, 0)
        getSearchSongList(this.query, this.page).then((res) => {
          const data = res.data.data
          this.result = this._formateData(data)
        })
      },
      // 格式化获得的数据
      _formateData (data) {
        let ret = []
        // 先放入歌手
        if (data.zhida.zhida_singer && data.zhida.zhida_singer.singerID) {
          ret.push({...data.zhida.zhida_singer, ...{type: SINGER}})
        }
        if (data.song) {
          ret = ret.concat(this._normalizeSongs(data.song.list))
        }
        if (data.song.list.length === 0) {
          this.hasMore = false
        }
        return ret
      },
      // 格式化歌曲
      _normalizeSongs (songs) {
        let ret = []
        songs.forEach(song => {
          if (song.songmid && song.songid) {
            ret.push(createSongForSearch(song))
          }
        })
        return ret
      },
      ...mapMutations({
        setSinger: 'SET_SINGER'
      }),
      ...mapActions([
        'insertSong'
      ])
    },
    watch: {
      query () {
        this._search()
      }
    },
    components: {
      Scroll,
      Loading,
      NoResult
    }
  }
</script>

<style scoped lang="stylus">
  @import "~common/stylus/variable.styl"
  @import "~common/stylus/mixin.styl"
  .suggest
    height: 100%
    overflow: hidden

    .suggest-list
      padding: 0 30px

      .suggest-item
        display: flex
        align-items: center
        padding-bottom: 20px

        .icon
          flex: 0 0 30px
          width: 30px

          [class^='icon-']
            font-size: 14px
            color: $color-text-d

        .name
          flex: 1
          font-size: $font-size-medium
          color: $color-text-d
          overflow: hidden

          .text
            no-wrap()

    .no-result-wrapper
      position: absolute
      top: 50%
      width: 100%
      transform: translateY(-50%)
</style>
